using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace hub.Client
{
    using txcloud.sdk.Lighthouse;
    using tozhang.sdk;
    using hub.Core.Client.Extensions;
    using hub.data;
    using hub.Core.Client;
    using ExcelConfig.StoreAPI;
    using txcloud.sdk;
    using ExcelConfig;

    class Program
    {
        public static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            if (!Directory.Exists("config")) Directory.CreateDirectory("config");
            ConfigStoreHelper.EnterConfigStoreAPIConfig();
            ExcelConfigHelper.Enter("配置域");
            ExcelConfigHelper.Enter("配置名");
            TxCloudSDKHelper.EnterTxCloudAppConfig();

            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseWindowsService()
                .ConfigureServices((hostContext, services) =>
                {
                    FastTunnelClient.ReConnectFunction += FastTunnelClient_ReConnectFunction;
                    services.AddFastTunnelClient();
                });

        private static void FastTunnelClient_ReConnectFunction(object? sender, EventArgs e)
        {
            if (sender is FastTunnelClient client) client._logger.LogInformation("===== CHECK REMOTE Firewall =====");
            OpenFirewall();
        }

        public static int OpenFirewall()
        {
            var ip = NetworkAPI.ReadInternetIPv4();
            var firewallkey = HUB.config.Text("防火墙标识");

            var app = new Lighthouse();
            var firewall = app.ReadFirewall();
            var info = firewall.Rules.FirstOrDefault(t => t.FirewallRuleDescription == firewallkey);
            if (info != null && int.TryParse(info.Port, out var port))
            {
                ServerInfo.Port = int.Parse(info.Port);
                if (info.CidrBlock.Equals(ip)) return port; //已更新，推出
                info.CidrBlock = ip;
                app.UpdateFirewall(firewall);
                return port;
            }

            return 0;
        }
    }
}
